import { createRouter, createWebHistory } from 'vue-router'
import LoginView from '../views/LoginView.vue'
import MainLayout from '../views/MainLayout.vue'
import { ElMessage } from 'element-plus'

// 检查 token 是否过期
const isTokenExpired = (userInfo: any): boolean => {
  if (!userInfo || !userInfo.expiration) {
    return true
  }
  return Date.now() > userInfo.expiration
}

// 路由配置
const routes = [
  {
    path: '/login',
    name: 'login',
    component: LoginView,
    meta: { requiresAuth: false } // 不需要登录验证
  },
  {
    path: '/',
    component: MainLayout,
    meta: { requiresAuth: true }, // 需要登录验证
    children: [
      {
        path: '',
        name: 'home',
        component: () => import('../views/HomeView.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: '/profile',
        name: 'profile',
        component: () => import('../views/ProfileView.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: '/admin',
        name: 'admin',
        component: () => import('../views/AdminView.vue'),
        meta: { requiresAuth: true, role: 'administrator' }
      },
      {
        path: '/about',
        name: 'about',
        component: () => import('../views/AboutView.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: '/user',
        name: 'user',
        component: () => import('../views/UserView.vue'),
        meta: { requiresAuth: true }
      }
    ]
  },
  // 重定向到登录页
  {
    path: '/:pathMatch(.*)*',
    redirect: '/login'
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

// 全局前置守卫 - 路由权限控制
router.beforeEach((to, from, next) => {
  // 检查是否需要登录验证
  if (to.meta.requiresAuth) {
    // 获取用户信息
    const userInfoStr = localStorage.getItem('userInfo')

    if (userInfoStr) {
      const userInfo = JSON.parse(userInfoStr)

      // 检查 token 是否过期
      if (isTokenExpired(userInfo)) {
        // token 过期，清除用户信息并跳转到登录页
        localStorage.removeItem('userInfo')
        ElMessage.error('登录已过期，请重新登录')
        next('/login')
        return
      }

      // 检查是否需要特定角色权限
      if (to.meta.role) {
        if (userInfo.role === to.meta.role) {
          // 角色权限匹配，允许访问
          next()
        } else {
          // 角色权限不匹配，跳转到首页或提示无权限
          ElMessage.error('您没有访问此页面的权限')
          next('/')
        }
      } else {
        // 只需要登录，不需要特定角色权限
        next()
      }
    } else {
      // 未登录，跳转到登录页
      ElMessage.error('请先登录')
      next('/login')
    }
  } else {
    // 不需要登录验证的页面
    next()
  }
})

export default router
